const express = require('express');
const mysql = require('mysql2');
const bodyParser = require('body-parser');
const cors = require('cors');  // 引入 cors 包

const app = express();
app.use(bodyParser.json());
app.use(cors());  // 使用 cors 中间件

// 创建 MySQL 连接
const db = mysql.createConnection({
    host: 'localhost',
    user: 'root', // 替换为你的 MySQL 用户名
    password: 'root', // 替换为你的 MySQL 密码
    database: 'wordbook' // 使用你的数据库名
});

// 连接到数据库
db.connect(err => {
    if (err) {
        console.error('Error connecting to the database: ' + err.stack);
        return;
    }
    console.log('Connected to the database as id ' + db.threadId);
});

// 插入数据
app.post('/add-word', (req, res) => {
    const { word, attr, meanings, synonyms, difficulty } = req.body;
    const query = 'INSERT INTO words (word, attr, meanings, synonyms, difficulty) VALUES (?, ?, ?, ?, ?)';
    const values = [word, JSON.stringify(attr), JSON.stringify(meanings), JSON.stringify(synonyms), difficulty];

    db.query(query, values, (err, result) => {
        if (err) {
            console.error('Error inserting data: ', err);
            res.status(500).send('Error inserting data: ' + err.message);
            return;
        }
        res.send('Word added successfully');
    });
});

// 查询数据
app.get('/words', (req, res) => {
    const query = 'SELECT * FROM words ORDER BY difficulty DESC';
    db.query(query, (err, results) => {
        if (err) {
            console.error('Error fetching data: ', err);
            res.status(500).send('Error fetching data: ' + err.message);
            return;
        }
        res.json(results.map(row => ({
            id: row.id,
            word: row.word,
            attr: JSON.parse(row.attr),
            meanings: JSON.parse(row.meanings),
            synonyms: JSON.parse(row.synonyms),
            difficulty: row.difficulty
        })));
    });
});

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});
